package com.th.cash.th2.product

import android.content.Context
import android.text.TextUtils
import com.lxj.xpopup.core.BottomPopupView
import com.th.cash.databinding.PopupDateSelectionBinding
import java.text.SimpleDateFormat
import java.util.Calendar

class DateSelectionPopup(context: Context, private val title: String,val selectTime:String) : BottomPopupView(context) {

    var clickListener: ((String) -> Unit)? = null

    override fun getImplLayoutId(): Int {
        return com.th.cash.R.layout.popup_date_selection
    }

    override fun onCreate() {
        super.onCreate()

        val bind = PopupDateSelectionBinding.bind(popupImplView)

        bind.run {
            singleSelectionTitle.text = title

            datePicker.run {
                if (!TextUtils.isEmpty(selectTime)) {
                    selectedDate = getCalendar("dd/MM/yyyy",selectTime)
                }

                setStartDate(getCalendar("yyyy/MM/dd","1960/01/01"))
                setEndDate(getCalendar("yyyy/MM/dd","2044/12/31"))
            }
            /*                .setOnSelectedDateChangedListener(DateTimePickerView.OnSelectedDateChangedListener { date ->
                            *//*val year = date[Calendar.YEAR]
                val month = date[Calendar.MONTH]
                val dayOfMonth = date[Calendar.DAY_OF_MONTH]
                val hour = date[Calendar.HOUR_OF_DAY]
                val minute = date[Calendar.MINUTE]
                val dateString = String.format(
                    Locale.getDefault(),
                    "%d年%02d月%02d日%02d时%02d分",
                    year,
                    month + 1,
                    dayOfMonth,
                    hour,
                    minute
                )
                toast(dateString)*//*
            })*/

            singleSelectionSubmit.setOnClickListener {
                dismiss()
                try {
                    clickListener?.invoke(SimpleDateFormat("dd/MM/yyyy").format(datePicker.selectedDate.time))
                } catch (e: Exception) {
                    e.printStackTrace()
                    clickListener?.invoke("")
                }
            }
        }
    }

    private fun getCalendar(pattern:String,timeStr: String): Calendar {
        return Calendar.getInstance().apply {
            time = SimpleDateFormat(pattern).parse(timeStr)
        }
    }

}